package org.opens.util;

import cn.hutool.core.util.StrUtil;

import java.io.File;

public class PathUtil {

    /**
     * 获取当前类的运行所在路径
     */
    public static String getCurrentClassRunPath() {
        File file = new File(PathUtil.class.getResource("/").getPath());
        return file.getPath();
    }

    /**
     * 获取当前工程路径.
     * 当前文件的输出为: E:\idea-project\program_demo
     */
    public static String getCurrentProjectPath() {
        return System.getProperty("user.dir");
    }

    /**
     * 将多个路径组装成合法的路径
     * @param path 多个路径信息
     */
    public static String pathSplicing(String... path) {
        StringBuilder result = new StringBuilder();

        for (int i = 0; i < path.length; i++) {
            String pathTmp = removePathSuffix(path[i]);

            result.append(pathTmp);

            if (!pathTmp.contains(".")) {
                result.append(File.separator);
            }
        }

        return result.toString();
    }

    /**
     * 删掉路径左右两边的文件分隔符
     * removePathSuffix("/test"); 返回: test
     * removePathSuffix("/test/"); 返回: test
     * removePathSuffix("\\test/"); 返回: test
     * removePathSuffix("\\test\\"); 返回: test
     *
     * @param path 文件路径
     */
    private static String removePathSuffix(String path) {
        for (int i = 0; i < 2; i++) {
            path = StrUtil.removeSuffix(path, "\\");
            path = StrUtil.removeSuffix(path, "\\");

            path = StrUtil.removeSuffix(path, "/");
            path = StrUtil.removeSuffix(path, "/");

            path = StrUtil.removePrefix(path, "\\");
            path = StrUtil.removePrefix(path, "\\");

            path = StrUtil.removePrefix(path, "/");
            path = StrUtil.removePrefix(path, "/");
        }
        return path;
    }

    public static void main(String[] args) {
        System.out.println(getCurrentProjectPath());
        System.out.println(pathSplicing("C://s", "temp", "a", "b"));
    }

}
